﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using ResultManagement;
using System.Text;
using LuceneManager;
using NClassifier.Bayesian;
using System.Configuration;
using Notifying;
using System.IO;

namespace KnowFirstWebApplication
{
    public partial class Results : basePageSessionExpire
    {
        public const string USERNAME = "UserName";
        public const string CATEGORY = "Category";
       
        public const int NUMBER_OF_RESULTS_PER_PAGE = 20;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                

                DisplayDocumentTypeList();
                //Session[USERNAME] = "roeyaus";
                ResultManager rm = new ResultManager(new LuceneSettings(UIHelper.LoadIndexNodes().ToArray(), HttpContext.Current.Server.MapPath("~/App_Data/HebrewPrefixes.txt")));
                User User = GetUser();
                PopulateDateCombos();
                DisplayUserCategoryNames(User);
                cbOnlyUnread.Checked = true;
                PopulateDateCBs(DateTime.Now.Subtract(new TimeSpan(168, 0, 0)), DateTime.Now.Add(new TimeSpan(24, 0, 0)));
                if (User.Categories.Count > 0)
                {
                    ViewState[CATEGORY] = User.Categories[0].Name;
                    DisplaySelectedCategoryQueries();
                    DisplayCurrentCategoryResults();
                }
             
            }
        }


        public void PopulateDateCBs(DateTime FromDate, DateTime ToDate)
        {
            cbFromYear.Text = FromDate.Year.ToString();
            cbFromMonth.Text = FromDate.Month.ToString();
            cbFromDay.Text = FromDate.Day.ToString();
            cbToYear.Text = ToDate.Year.ToString();
            cbToMonth.Text = ToDate.Month.ToString();
            cbToDay.Text = ToDate.Day.ToString();
        }

        public void DisplayResults(List<Document> results)
        {
            lvCategoryResults.DataSource = results;
            lvCategoryResults.DataBind();
        }

        public DateTime GetFromDate()
        {
            return new DateTime(Int32.Parse(cbFromYear.Text),
                Int32.Parse(cbFromMonth.Text), Int32.Parse(cbFromDay.Text));
        }
        public DateTime GetToDate()
        {
            return new DateTime(Int32.Parse(cbToYear.Text),
                Int32.Parse(cbToMonth.Text), Int32.Parse(cbToDay.Text));
        }

        /// <summary>
        /// Gets current user
        /// </summary>
        /// <returns>current user's object</returns>
        User GetUser()
        {
            return GetUser(Session[USERNAME] as string);
        }

        public static User GetUser(string userName)
        {
            Dal.DatabaseAbstractionLayer dal = new Dal.DatabaseAbstractionLayer();
            User User = dal.GetUserByUserName(userName);
            return User;
        }




        Category GetCurrentCategory()
        {
            User User = GetUser();
            return User.GetCategoryByName(ViewState[CATEGORY] as string);
        }

        private void DisplayCurrentCategoryResults()
        {
             User User = GetUser();
             DisplayResultsByCategory(User.UserName, 
                 ViewState[CATEGORY] as string, GetSelectedQueries(), 0,
                 NUMBER_OF_RESULTS_PER_PAGE);
        }

        private void DisplayResultsByCategory(string userName, string categoryName,
            List<string> queries, int pageNumber, int numOfResultsPerPage)
        {
            ResultManager rm = new ResultManager(new LuceneSettings(UIHelper.LoadIndexNodes().ToArray(), HttpContext.Current.Server.MapPath("~/App_Data/HebrewPrefixes.txt")));
            bool isread = !cbOnlyUnread.Checked;
            int totalDocNumber;
            List<Document> results = rm.GetUserCategoryResults(userName, GetSelectedQueries(),
                GetUser(userName).GetCategoryByName(categoryName), isread,
                pageNumber * numOfResultsPerPage,
                pageNumber * numOfResultsPerPage + numOfResultsPerPage, 
                out totalDocNumber);
            results = rm.FilterResultsByDocumentTypes(results, GetSelectedDocTypes());
            results = Document.FilterDocumentsByDate(results, GetFromDate(), GetToDate());
            results = Document.SortDocumentsByPriorityDate(results);
            //results = rm.GetExcerpts(results, queries,
                 //ResultsDataPager.StartRowIndex,
                //ResultsDataPager.StartRowIndex + ResultsDataPager.PageSize);
            DisplayCategoryName(categoryName, NUMBER_OF_RESULTS_PER_PAGE, 
                totalDocNumber);
            DisplayResults(Document.SortDocumentsByPriorityDate(results));
        }

        private List<string> GetSelectedQueries()
        {
            List<string> res = new List<string>();
            foreach (ListItem li in lbSelectedQueries.Items)
            {
                res.Add(li.Value);
            }
            return res;
        }



        public void DisplayDocumentTypeList()
        {
            cblDocumentTypes.DataSource = Document.GetDocumentTypesNameList();
            cblDocumentTypes.DataBind();
            foreach (ListItem li in cblDocumentTypes.Items)
                li.Selected = true;
        }

        private void DisplayCategoryName(string categoryName, int numResPerPage, 
            int totNumRes)
        {

            lblCategoryName.Text = String.Format("קטגוריה: {0}, מציג {3}-{1} תוצאות מתוך {2}. ", categoryName,
                ResultsDataPager.StartRowIndex, totNumRes, ResultsDataPager.StartRowIndex + ResultsDataPager.PageSize);
            lblCategoryName.Font.Bold = true;
        }

        private void DisplayUserCategoryNames(User User)
        {
            lbCategories.Items.Clear();
            lbCategories.DataSource = User.Categories;
            lbCategories.DataBind();
            lbCategories.SelectedIndex = 0;
        }

        private List<Document.Type> GetSelectedDocTypes()
        {
            List<Document.Type> docTypes = new List<Document.Type>();
            for (int i = 0; i < cblDocumentTypes.Items.Count; i++)
            {
                if (cblDocumentTypes.Items[i].Selected)
                    docTypes.Add((Document.Type)i);
            }
            return docTypes;
        }


        private void PopulateDateCombos()
        {
            cbFromDay.DataSource = UIHelper.GetDaysInMonth();
            cbFromDay.DataBind();
            cbFromMonth.DataSource = UIHelper.GetMonthesInYear();
            cbFromMonth.DataBind();
            cbFromYear.DataSource = UIHelper.GetYearsFrom1990To2020();
            cbFromYear.DataBind();
            cbToDay.DataSource = UIHelper.GetDaysInMonth();
            cbToDay.DataBind();
            cbToMonth.DataSource = UIHelper.GetMonthesInYear();
            cbToMonth.DataBind();
            cbToYear.DataSource = UIHelper.GetYearsFrom1990To2020();
            cbToYear.DataBind();

        }

        protected void btnLoadCategory_Click(object sender, EventArgs e)
        {
            ViewState[CATEGORY] = lbCategories.SelectedValue;
            DisplayCurrentCategoryResults();
        }
        protected void lvCategoryResults_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        {
            ResultsDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
            DisplayCurrentCategoryResults();
        }

        protected void cblDocumentTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState[CATEGORY] = lbCategories.SelectedValue;
            DisplayCurrentCategoryResults();
        }

        protected void lvCategoryResults_SelectedIndexChanged(object sender, EventArgs e)
        {
            NClassifier.Bayesian.BayesianClassifier c = new
               NClassifier.Bayesian.BayesianClassifier(new SqlWordsDataSource
                   (new SqlConnectionManager(
                     ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)));
            ListViewDataItem currentItem = (ListViewDataItem)((DropDownList)sender).Parent;

            long id = (long)this.lvCategoryResults.DataKeys[currentItem.DataItemIndex].Value;
            LuceneReader reader = new LuceneReader(UIHelper.LoadIndexNodes().ToArray());
            Document doc = reader.GetDocumentById(id);
            
            DropDownList ddl = (DropDownList)sender;
            doc.SentimentId = ddl.SelectedIndex;
            //lm.AddDocument(doc);
            //lm.CloseIndexWriter();
            //lm.CloseAllFiles();
            switch (ddl.SelectedIndex)
            {
                case 1:
                    {
                        c.TeachMatch(ddl.Items[1].Text, doc.Text);
                        c.TeachNonMatch(ddl.Items[0].Text, doc.Text);
                        c.TeachNonMatch(ddl.Items[2].Text, doc.Text);
                        break;
                    }
                case 2:
                    {
                        c.TeachMatch(ddl.Items[2].Text, doc.Text);
                        c.TeachNonMatch(ddl.Items[1].Text, doc.Text);
                        c.TeachNonMatch(ddl.Items[0].Text, doc.Text);
                        break;
                    }
            }
           
        }

        protected void cbOnlyUnread_CheckedChanged(object sender, EventArgs e)
        {
            DisplayCurrentCategoryResults();
        }


        protected void btnAddQuery_Click(object sender, EventArgs e)
        {
            if (!lbSelectedQueries.Items.Contains(new ListItem(lbQueries.SelectedValue)))
                lbSelectedQueries.Items.Add(new ListItem(lbQueries.SelectedValue));
        }
        protected void btnRemoveQuery_Click(object sender, EventArgs e)
        {
            lbSelectedQueries.Items.Remove(new ListItem(lbSelectedQueries.SelectedValue));
        }

        protected void lbCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            DisplaySelectedCategoryQueries();
        }

        public void DisplaySelectedCategoryQueries()
        {
            User user = GetUser();
            Category cat = user.GetCategoryByName(lbCategories.SelectedValue);
            lbQueries.DataSource = cat.Queries;
            lbQueries.DataBind();
            lbSelectedQueries.DataSource = cat.Queries;
            lbSelectedQueries.DataBind();
        }

        public static string ArrangeExcerpts(string[] Excerpts)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in Excerpts)
            {
                sb.Append(String.Format("{0}<br>", s));
            }
            return sb.ToString();


        }

        protected void ResultsDataPager_PreRender(object sender, EventArgs e)
        {

        }

    }
}
